import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { login, findUserByUsername, logout } from '@/api/login'
import { ACCESS_TOKEN, USER_NAME } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    username: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_USERNAME: (state, { username }) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ commit, dispatch }, userInfo) {
      return new Promise( (resolve, reject) => {
        login(userInfo).then(async result => {
          storage.set(ACCESS_TOKEN, result.accessToken, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
          window.sessionStorage.setItem(ACCESS_TOKEN, result.accessToken)
          commit('SET_TOKEN', result.accessToken)
          storage.set(USER_NAME, userInfo.username, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
          commit('SET_USERNAME', userInfo)
          const userinfo = await dispatch('GetInfo')
          resolve(userinfo)
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        const username = state.username
        findUserByUsername({
          username
        }).then(res => {
          const { roleList, username, avatar, ...info } = res
          commit('SET_INFO', { name: username, username, ...info })
          commit('SET_ROLES', roleList)
          commit('SET_NAME', { name: username, welcome: welcome() })
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, dispatch, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_INFO', null)
          commit('SET_NAME', { name: null, welcome: welcome() })
          storage.remove(ACCESS_TOKEN)
          window.localStorage.clear()
          window.sessionStorage.clear()
          resolve()
        }).catch((err) => {
          // resolve()
        }).finally(() => {
        })
      })
    }

  }
}

export default user
